//
//  HomepageViewController.swift
//  LongTermInsurance
//
//  Created by DYD on 2018/11/9.
//  Copyright © 2018 HeChao. All rights reserved.
//

import UIKit
import MJRefresh
import ObjectMapper

class HomepageViewController: BaseTableViewController {

    lazy var headerView: HomepageHeaderView = {
        let view = Bundle.main.loadNibNamed("HomepageHeaderView", owner: nil
            , options: nil)!.last as! HomepageHeaderView
        let h = 200 + 10 + DeviceInfo.screenWidth / 2 - 20 + 10 + 80 + 20
        view.frame = CGRect(x: 0, y: 0, width: DeviceInfo.screenWidth, height: h)
        return view
    }()
    
    var notifyArray = [NotifyModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "首页"
        view.backgroundColor = .white
        // Do any additional setup after loading the view.
        
        tableView.register(UINib(nibName: "NotifyTableViewCell", bundle: nil), forCellReuseIdentifier: "NotifyTableViewCell")
        tableView.estimatedRowHeight = 0
        tableView.rowHeight = 50
        
        header.isHidden = false
        
        tableView.tableHeaderView = headerView
        tableView.reloadData()
        header.beginRefreshing()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let info = MyselfSingleton.shared.userInfo {
            headerView.avatarImageView.image = info.sex == "男" ? R.image.gender_male() : R.image.gender_female()
            headerView.nameLabel.text = info.name
        }
    }
    
    
    override func pullRefresh() {
        getBannerData()
        getNotifyData()
    }
    
    override func loadMore() {
    }
    
    func getBannerData() {
        let values = ["APPLB": "1"].convertToJsonString()
        
        let paramString = "<json>"+values+"</json>"
        
        NetworkingHandle.fetchNetworkData(method: "getFlexSilderInfo", paramString: paramString, success: {[weak self] (dict) in
            if let code = dict["ResultCode"] as? Int,code == 0 {
                var imgArray = [String]()
                var urlArray = [String]()
                if let imgsString = dict["PicUrls"] as? String, let imgArr = imgsString.convertToObject() as? [String] {
                    imgArray = imgArr
                }
                if let urlString = dict["HttpUrls"] as? String, let urlArr = urlString.convertToObject() as? [String]  {
                    urlArray = urlArr
                }
                var tempArray = [BannerModel]()
                if imgArray.count == urlArray.count {
                    for (index,img) in imgArray.enumerated() {
                        let model = BannerModel()
                        model.img = img
                        model.url = urlArray[index]
                        tempArray.append(model)
                        imgArray.append(img)
                    }
                } else {
                    imgArray = [String]()
                }
                
                self?.headerView.bannerArray = tempArray
                self?.headerView.banner.imageURLStringsGroup = imgArray
                return
            }
            if let code = dict["ResultCode"] as? Int,code == 1 {
                if let msgString = dict["ResultMessage"] as? String {
                    CDUtility.showMSG(message: msgString)
                }
            }
        }) {
            print("")
        }
    }
    
    func getNotifyData() {
        let values = ["APPLB": "1"].convertToJsonString()
        
        let paramString = "<json>"+values+"</json>"
        
        NetworkingHandle.fetchNetworkData(method: "getNoticeList", paramString: paramString, success: {[weak self] (dict) in
            self?.header.endRefreshing()
            if let code = dict["ResultCode"] as? Int,code == 0 {
                if let imgsString = dict["NoticeLists"] as? String {
                    if let array = Mapper<NotifyModel>().mapArray(JSONString: imgsString.lowercased()) {
                        self?.notifyArray = array
                        self?.tableView.reloadData()
                    }
                }
                return
            }
            if let code = dict["ResultCode"] as? Int,code == 1 {
//                if let msgString = dict["ResultMessage"] as? String {
//                    CDUtility.showMSG(message: msgString)
//                }
            }
        }) {
            self.header.endRefreshing()
            print("")
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return notifyArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NotifyTableViewCell", for: indexPath) as! NotifyTableViewCell
        cell.model = notifyArray[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = Bundle.main.loadNibNamed("HomeSectionHeaderView", owner: nil
            , options: nil)!.last as! HomeSectionHeaderView
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = notifyArray[indexPath.row]
        let vc = NotifyDetailViewController()
        vc.notifyID = model.notifyNO
        navigationController?.pushViewController(vc, animated: true)
    }

}
